package go_captcha

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/wenlng/go-captcha/captcha"
	"go-shop-admin/pkg/e"
	"go-shop-admin/pkg/serializer"
	"io"
	"os"
	"time"
)

//验证码 - 未使用
//官方 https://github.com/dchest/captcha
//获得 go get github.com/dchest/captcha
//参考 https://zhuanlan.zhihu.com/p/382744512

//行为式验证码 - 使用
//官方 https://github.com/wenlng/go-captcha/blob/master/README_zh.md
//获得  go get -u github.com/wenlng/go-captcha/captcha
//文档  https://github.com/wenlng/go-captcha/blob/master/README_zh.md
//      doc.md  使用go get * 下拉后，在本地会有一个github.com/wenlng/go-captcha/go_captcha 中有文档

// GetVerifyCode 获取实例
func GetVerifyCode() *serializer.Response {
	capt := captcha.GetCaptcha()

	dots, b64, tb64, key, err := capt.Generate()
	if err != nil {
		return serializer.NewResponse(e.ErrorGetCaptcha, "GenCaptcha err", e.TipsErrorGetCaptcha, nil)
	}
	WriteCache(dots, key)
	//fmt.Println(json.Marshal(dots)) 打印主点

	return serializer.NewResponse(e.Success, e.TipsOk, e.TipsSuccessGetCaptcha, gin.H{
		"image_base64": b64,
		"thumb_base64": tb64,
		"captcha_key":  key,
	})

	//bt, _ := json.Marshal(map[string]interface{}{
	//	"code":         0,
	//	"image_base64": b64,
	//	"thumb_base64": tb64,
	//	"captcha_key":  key,
	//})
	//_, _ = fmt.Fprintf(w, string(bt))
}

/*WriteCache 写入缓存
 * @Description: Write Cache，“Redis” is recommended
 * @param v
 * @param file
 */
func WriteCache(v interface{}, file string) {
	bt, _ := json.Marshal(v)
	month := time.Now().Month().String()
	cacheDir := getCacheDir() + month + "/"
	_ = os.MkdirAll(cacheDir, 0660)
	file = cacheDir + file + ".json"
	logFile, _ := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	defer logFile.Close()
	// 检查过期文件
	//checkCacheOvertimeFile()
	_, _ = io.WriteString(logFile, string(bt))
}

/**
 * @Description: Get cache dir path
 * @return string
 */
func getCacheDir() string {
	return getPWD() + "/runtime/cache/"
}

/**
 * @Description: Get pwd dir path
 * @return string
 */
func getPWD() string {
	path, err := os.Getwd()
	if err != nil {
		return ""
	}
	return path
}
